﻿using System;

using zijian666.Converts.Abstractions;
using zijian666.Converts.Core;
using zijian666.Converts.Extensions;

namespace zijian666.Converts.Convertor;

/// <summary>
/// <seealso cref="Nullable{T}"/> 可空值类型转换器
/// </summary>
public class NullableConvertor<TValue> : IConvertor<TValue?>
    where TValue : struct
{

    /// <inheritdoc/>
    public uint Priority { get; } = 1;

    /// <inheritdoc/>
    public ConvertResult<TValue?> Convert(IConvertContext context, object? input)
    {
        if (input is null || input is DBNull || (input is string s && string.IsNullOrWhiteSpace(s)))
        {
            return new (null);
        }
        var result = context.Convert<TValue>(input);
        return result.Success ? new (result.Value) : (ConvertResult<TValue?>)result.Exception!;
    }
}
